package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.pub.dbservice.IDBService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import nccloud.bs.log.LogVO;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;

/**
 * <p>同步财政系统</p>
  *  单位帐套信息
 * @author Administrator
 * @date 2024年2月26日
 */
public class UnitAccountWriteBackgroundWorkPlugin extends AbstractBackgroundWorkPlugin {
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;
	
	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		List<Map<String, Object>> lists = queryData(buildSQL(keyMap));
		try {
			List<List<Map<String,Object>>> listparams = super.getGroupAfterData(lists);
			if(listparams == null ) return;
			// 对分组的数据进行推送
			for(List<Map<String, Object>> params : listparams) {
				List<LogVO> listVOs = new ArrayList<>();
				String message = null;
				String issuccess = "Y";
				String result = null;
				try {
					String param = super.getParam(buildParam(params,listVOs),"DWKJHS01", super.getAppid()); // 每十行数据合并在一起推送
					if(param == null || "".equals(param)) return;
					if(param == null) return;
					result = HttpReqUtils.sendPost(getURL("DEF001"), param);
					getLog().info("----第四步接口响应结果::" + result);
					JSONObject jsonres = JSONObject.parseObject(result);
					Object code = jsonres.get("code");
					if("200".equals(code)) {
						message = "同步成功";
					}else {
						message = jsonres.getString("msg"); 
						issuccess = "N";
						result = jsonres.toString();
					}
					
				}catch(Exception e) {
					message = e.getMessage();
					issuccess = "N";
				}finally {
					for(LogVO vo : listVOs) {
						vo.setIssuccess(issuccess);
						vo.setError(message);
						vo.setVdef2(result);
					}
					
					getDbService().insertVOList(listVOs);
				}
			}
		}catch(Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("unitAccount");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数、类型:"+ keyMap.get("type")+",开始日期:"+keyMap.get("begindate")+"结束日期:"+keyMap.get("enddate")+",同步频率:"+keyMap.get("synctime"));
			vo.setError("单位帐套同步:"+e.getMessage());
			getDbService().insertVO(vo);
		}
		
	}
	
	/**
	 * 获取第三方同步地址
	 * @param initCode
	 * @return
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception{
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000",initCode)+"/pty/gla-dec/v1/account/acctsets";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 * @return
	 */
	public IDBService getDbService() {
		if(dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	/**
	 * 构建数据查询sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("rawtypes")
	public String buildSQL(Map keyMap) throws BusinessException{
		StringBuilder sb = new StringBuilder();
		if(keyMap != null && !keyMap.isEmpty()) {
			sb.append("select ");
			sb.append("	oos.pk_org pk_org,oos.pk_vid pk_org_v, oos.pk_group, oos.code vbillcode , oos.code code,  ");
			sb.append("	oos.name orgname,  oos.creator, ");
			sb.append(" oos.creationtime, oos.modifier, oos.modifiedtime,  ");
			sb.append(" oos.enablestate, oos.vstartdate, bd_countryzone.name countname,");
			sb.append("  sm.user_code usercode, sm.user_name username, ");
			sb.append("  ");
			sb.append(" oos.dr, oos.ts  ");
			sb.append("from org_orgs oos ");
			sb.append(" inner join sm_user sm on sm.cuserid = oos.creator ");
			sb.append("  left join bd_countryzone on oos.countryzone = bd_countryzone.pk_country ");
			sb.append(" where (oos.pk_org = 'GLOBLE00000000000000' or oos.pk_group = '0001A210000000000JB9') ");
			sb.append("  and (oos.pk_group = '0001A210000000000JB9' and oos.isbusinessunit = 'Y' and  oos.enablestate = 2 ) and oos.dr = 0 ");
			Object startdate = null;
			Object stopdate = null;
			Object type = keyMap.get("type");
			if("1".equals(type)) { //  [指定时间段拉取,1];[拉指定的一天,2];
				Object begindate = keyMap.get("begindate")  == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				Object enddate = keyMap.get("enddate") == null  ? ymd.format(new Date()) : keyMap.get("enddate") ;
				startdate = begindate + " 00:00:00";
				stopdate = enddate + " 23:59:59";
			}else if("2".equals(type)) { // [拉指定的一天,2]
				Object begindate = keyMap.get("begindate") == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				startdate = begindate + " 00:00:00";
				stopdate = begindate + " 23:59:59";
			}else { // [定时执行, ] 默认同步频率30分钟  
		        Calendar calendar = Calendar.getInstance();
		        stopdate = ymdsfm.format(calendar.getTime());//当前时间
		        Object synctime = keyMap.get("synctime"); //  同步频率
		        if(synctime ==  null ) {
			        calendar.add(Calendar.MINUTE, -30); // time 的前几分钟
		        }else {
	        		int time = Integer.parseInt(synctime.toString());
			        calendar.add(Calendar.MINUTE, -time); // time 的前几分钟
		        }
		        startdate = ymdsfm.format(calendar.getTime());
			}
			sb.append(" and oos.ts between '"+startdate+"' and '"+stopdate+"' ");
			return sb.toString();
		}
		return null;
	}

	/**
	 * 查询需要同步的数据
	 * @param sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>>  queryData(String sql)  throws BusinessException{
		if(sql == null) return null;
		List<Map<String, Object>> lists = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		return lists == null ||  lists.isEmpty() ? null : lists;
	}
	
	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	public JSONArray buildParam(List<Map<String, Object>> data,List<LogVO> listVOs) throws Exception{
		if(data == null) return null;
		JSONArray jsonArray = new JSONArray();
		for(Map<String, Object> map : data) {
			JSONObject json = new JSONObject();
			json.put("ACCT_SET_ID", ToolUtils.getJudgeAttribute(map.get("pk_org")));  // 帐套唯一标识
			json.put("ACCT_SET_CODE", super.getAccount()); 
			json.put("ACCT_SET_TYPE", 1); // 账套类型
			json.put("AGENCY_CODE", super.getUnit()); //单位代码
			json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
			json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
			json.put("SET_YEAR", map.get("vstartdate") == null ? 
					ymd.format(new Date()).split("-")[0] : map.get("vstartdate").toString().split("-")[0]); //会计年度
			json.put("START_DATE", super.getYMD(map.get("vstartdate"))); // 启用日期
			json.put("IS_ENABLED", "2".equals(map.get("enablestate")) ? 1: 0); // 0 停用  1 启用 
			json.put("FI_LEADER", ToolUtils.getJudgeAttribute(map.get("fi_leader"))); // 财务负责人
			json.put("UPDATE_TIME", ToolUtils.getJudgeAttribute(map.get("modifiedtime")));
			json.put("CREATE_USER", ToolUtils.getJudgeAttribute(map.get("username")));
			json.put("CREATE_TIME", ToolUtils.getJudgeAttribute(map.get("creationtime")));
			json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE()); // 区划
			json.put("IS_DELETED", map.get("dr") == Integer.valueOf(0) ? 2 : 1); // 1已删除 2 未删除
			LogVO logVO = getDbService().buildLogVO(map, json, "financial", "unitAccount");
			listVOs.add(logVO);
			jsonArray.add(json);
		}
		return jsonArray;
	}
	
	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}

}
